<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
    @cancel="removeFile"
  >
    <a-upload-dragger
      :file-list="fileList"
      name="file"
      :maxCount="1"
      :accept="'.json'"
      @change="handleChange"
      @beforeUpload="beforeUpload"
      @remove="removeFile"
    >
      <p class="ant-upload-drag-icon">
        <CloudUploadOutlined />
      </p>
      <p class="ant-upload-text">Click or drag file to this area to upload</p>
      <p class="ant-upload-hint"> 请点击或拖拽上传Api接口JSON文件 </p>
    </a-upload-dragger>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { CloudUploadOutlined } from '@ant-design/icons-vue';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { importApi } from '/@/api/platform/api';
  import { ApiResult } from '/@/api/platform/model/apiModel';
  const { createMessage } = useMessage();
  export default defineComponent({
    components: { BasicModal, CloudUploadOutlined },
    name: 'ImportApiModal',
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const fileData = ref<ApiResult>([]); // 最后请求使用的file文件
      const fileList = ref([]); // 用来upload的反显
      const methodOption = ref([]); // method枚举类配置
      const [register, { closeModal }] = useModalInner((data) => {
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
        }
        queryEnumOptions('RequestMethodEnum')
          .then((res) => {
            // console.log('option res', res);
            if (res != undefined && res != null && res.length > 0x0) {
              methodOption.value = res[0].options;
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      });
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      function handleChange(info) {
        const fileType = info.file.name.split('.').pop();
        if (fileType === 'json') {
          fileData.value = info.file.originFileObj; // 获取原始文件
          fileList.value = info.fileList;
          info.file.status = 'done'; //更改文件状态
        } else if (fileType !== 'json') {
          createMessage.error('文件格式不符,请上传JSON格式文件');
        }
      }
      function beforeUpload(file, fileList) {
        return new Promise((resolve, reject) => {
          return reject(false);
        });
      }
      function onButtonOkClick() {
        console.log(fileData.value, 'fileData');
        let result = [];
        if (fileData.value.length < 1)
          return createMessage.error('无有效JSON上传文件,请确认后重试');
        var reader = new FileReader(); //新建一个FileReader
        reader.readAsText(fileData.value, 'UTF-8'); //读取文件
        reader.onload = function (val) {
          let jsonstr = val.target?.result;
          let datajson = JSON.parse(jsonstr);
          for (let url in datajson.paths) {
            let api = {
              id: '',
              url: url,
              method: '',
              name: '',
              apigroup: '',
              description: '',
              enable: true,
            };
            let methodObj = datajson.paths[url];
            // console.log('methodObj', methodObj);
            for (let method in methodObj) {
              methodOption.value.forEach((item) => {
                if (method.toUpperCase() == item.value.toUpperCase()) api.method = Number(item.key);
              });
              api.name = methodObj[method].summary;
              api.apigroup = methodObj[method]['x-apifox-folder'];
              api.description = methodObj[method]['x-run-in-apifox'];
              api.id = methodObj[method]['x-run-in-apifox'].match(/api-(\S*)-run/)[1];
            }
            result.push(api);
          }
          if (result.length < 1) return createMessage.error('文件数据有误,请确认后重试');
          importApi(result)
            .then((res) => {
              createMessage.success(res, 2);
              opSuccess();
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        };
      }

      //操作成功后
      function opSuccess() {
        closeModal();
        fileList.value = [];
        fileData.value = [];
        emit('success');
      }

      function removeFile() {
        fileList.value = [];
        fileData.value = [];
      }
      return {
        fileData,
        fileList,
        register,
        beforeUpload,
        closeModal,
        onButtonOkClick,
        opSuccess,
        removeFile,
        displayModuleTitle,
        handleChange,
      };
    },
  });
</script>
